package com.hdu.dwh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.dwh.pojos.User;
//import com.hdu.dwh.enums.ApiErrorCode;
//import com.hdu.dwh.exception.ApiException;
import com.hdu.dwh.mapper.UserMapper;
import com.hdu.dwh.service.UserService;
import com.hdu.dwh.utils.OperatorUtil;
import com.hdu.dwh.results.ResponseResult;
import com.hdu.dwh.vos.UserVo.UserOperationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     */
    @Override
    public ResponseResult<User> register(String username, String password) {

//        // 校验 userType 是否有效
//        if (!"admin".equals(usertype) && !"user".equals(usertype)) {
//            return ResponseResult.fail(400, "无效的用户权限类型");
//        }

        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            return ResponseResult.fail(400, "用户名已存在");
        }

        // 创建新用户并插入数据库
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 建议加密存储
        newUser.setUsertype("user"); // 默认为普通用户
        int insertResult = userMapper.insert(newUser);

        if (insertResult > 0) {
            return ResponseResult.success("注册成功", newUser);
        } else {
            return ResponseResult.fail(500, "注册失败");
        }
    }

    /**
     * 用户登录
     */
    @Override
    public ResponseResult<User> login(String username, String password) {
        // 参数校验
        if (username == null || username.trim().isEmpty()) {
            return ResponseResult.fail(400, "用户名不能为空");
        }

        if (password == null || password.isEmpty()) {
            return ResponseResult.fail(400, "密码不能为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            return ResponseResult.fail(404, "用户不存在");
        }

        if (!user.getPassword().equals(password)) {
            return ResponseResult.fail(401, "密码错误");
        }

        return ResponseResult.success("登录成功", user);
    }


    /**
     * 删除用户
     */
    @Transactional
    @Override
    public ResponseResult<UserOperationVo> deleteUser(String username) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        int deleteResult = userMapper.delete(queryWrapper);

        if (deleteResult > 0) {
            UserOperationVo vo = new UserOperationVo();
            vo.setUser(user);
            vo.setOperator(OperatorUtil.getCurrentOperator());
            return ResponseResult.success(200, "删除成功", vo);
        } else {
            return ResponseResult.fail(404, "用户不存在或删除失败");
        }
    }

    /**
     * 修改用户密码
     */
    @Override
    public ResponseResult<UserOperationVo> updatePassword(String username, String newPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            return ResponseResult.fail(404, "用户不存在");
        }

        user.setPassword(newPassword);
        int updateResult = userMapper.update(user, queryWrapper);

        if (updateResult > 0) {
            UserOperationVo vo = new UserOperationVo();
            vo.setUser(user);  // 设置被删除的用户信息
            vo.setOperator(OperatorUtil.getCurrentOperator());
            return ResponseResult.success(200, "密码修改成功", vo);
        } else {
            return ResponseResult.fail(500, "密码修改失败");
        }
    }

    /**
     * 修改用户类型（权限）
     */
    @Override
    public ResponseResult<UserOperationVo> updateUsertype(String username, String newUsertype) {
        // 校验 userType 是否有效
        if (!"admin".equals(newUsertype) && !"user".equals(newUsertype)) {
            return ResponseResult.fail(400, "无效的用户类型");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            return ResponseResult.fail(404, "用户不存在");
        }

        user.setUsertype(newUsertype); // 更新用户类型
        int updateResult = userMapper.update(user, queryWrapper);

        if (updateResult > 0) {
            UserOperationVo vo = new UserOperationVo();
            vo.setUser(user);
            vo.setOperator(OperatorUtil.getCurrentOperator());
            return ResponseResult.success(200, "用户权限修改成功", vo);
        } else {
            return ResponseResult.fail(500, "用户权限修改失败");

        }
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 管理员新增用户
     */
    @Override
    public ResponseResult<UserOperationVo> addUser(String username, String password, String usertype) {
        // 校验 userType 是否有效
//        if (!"admin".equals(usertype) && !"user".equals(usertype)) {
//            return ResponseResult.fail(400, "无效的用户权限类型");
//        }

        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            return ResponseResult.fail(400, "用户名已存在");
        }

        // 使用BeanUtils.copyProperties创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 建议加密存储
        newUser.setUsertype(usertype);
        
        // 使用save()方法，MyBatis-Plus会自动处理ID生成
        boolean saveResult = this.save(newUser);

        if (saveResult) {
            UserOperationVo vo = new UserOperationVo();
            vo.setUser(newUser);  // 设置被删除的用户信息
            vo.setOperator(OperatorUtil.getCurrentOperator());
            return ResponseResult.success(200, "新增用户成功", vo);
        } else {
            return ResponseResult.fail(500, "新增用户失败");
        }
    }

}